package com.zw.yzk.kabu.presenter;

import android.support.v7.app.AppCompatActivity;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseApplication;
import com.zw.yzk.kabu.base.BaseSubscriber;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.network.entity.SkinListEntity;
import com.zw.yzk.kabu.data.network.task.SkinListTask;
import com.zw.yzk.kabu.domain.repository.UseCase;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.mapper.SkinListMapper;
import com.zw.yzk.kabu.model.SkinModel;
import com.zw.yzk.kabu.view.view.SkinListView;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;

/**
 * Created by skydar on 2017/4/14.
 */

public class SkinListPresenter implements Presenter {

    private UseCase useCase;
    private AppCompatActivity activity;
    private SkinListView view;
    private SkinListMapper mapper;

    @Inject
    public SkinListPresenter(@Named("skinListUseCase") UseCase useCase,
                             AppCompatActivity activity, SkinListMapper mapper) {
        this.useCase = useCase;
        this.activity = activity;
        this.mapper = mapper;
    }

    public void setView(SkinListView view){
        this.view = view;
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        if(useCase != null) useCase.unSubscribe();
    }

    public void getSkinList(int start, int lastId) {
        useCase.execute(new Subscriber(activity), new SkinListTask(
                start,
                activity.getIntent().getIntExtra(ActivityConstant.SKIN_CATEGORY_ID, 0),
                lastId));
    }

    private class Subscriber extends BaseSubscriber<SkinListEntity> {

        public Subscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public String addErrorMessage() {
            return BaseApplication.getInstance().getResources().getString(R.string.get_skin_failed);
        }

        @Override
        public void onNext(SkinListEntity entity) {
            super.onNext(entity);
            List<SkinModel> models = mapper.transfer(entity);
            view.showSkinList(models);
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            view.fetchFailed();
        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }
    }


}
